<template>
     <el-dialog width="63%" destroy-on-close :show-close="false" center class="packDialog">
                <div class="packContent">
                    <div class="packHead">
                        <div class="packName">{{ modalItemData.goodsName }}</div>
                        <!-- <div class="packPrice">￥<span>1000</span>.00</div> -->
                        <div class="packPrice">￥<span>{{ modalItemData.salePrice }}</span></div>
                    </div>
                    <div class="packBody">
                        <div class="packLeft">
                            <div class="packTip">套餐包含以下菜品</div>
                            <div style="width: 100%; overflow-x: hidden;">
                                <div class="packList">
                                    <div class="packItem" v-for="(item, index) in modalItemData.priceList[0].detail"
                                        :key="index" :class="{ packItemChose: index == PackIndex }"
                                        @click="chosePack(item.goodsDetail, index)">
                                        <div class="groupTop" v-if="item.operType == '1'">
                                            <div class="groupName">{{ item.groupName }}</div>
                                            <div class="groupCount">固定搭配</div>
                                        </div>
                                        <div class="groupTop" v-if="item.choiceType == '0' && item.operType == '0'">
                                            <div class="groupName">{{ item.groupName }}</div>
                                            <div class="groupCount">可选数量<span>{{ item.maxQty }}</span>，已选<span
                                                    style="color: #FF6A00;">{{ item.allQty }}</span></div>
                                        </div>
                                        <div class="groupTop" v-if="item.choiceType == '1' && item.operType == '0'">
                                            <div class="groupName">{{ item.groupName }}</div>
                                            <!-- <div class="groupCount">可选种类<span>{{ item.maxQty }}</span>，已选<span
                                                    style="color: #FF6A00;">{{ item.allQty }}</span></div> -->
                                            <div class="groupCount">可选种类<span>{{ item.maxQty }}</span></div>
                                        </div>
                                        <div class="groupbottom" v-for="(i, s) in item.goodsDetail" :key="s">
                                            <div class="groupGoods">
                                                <div class="goodsName">{{ i.goodsName }}</div>
                                                <div class="goodsCount">{{ i.defaultQty }}</div>
                                                <div class="goodsunit">{{ i.uomName }}</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
              
                        <div class="packRight">
                            <div class="allocationTip" v-if="PackDetail">套餐配置</div>
                            <div class="allocationList" v-if="PackDetail">
                                <!-- <div class="allocationItem" v-for="(item, index) in PackDetail" :key="index">
                        
                                    <div :class="{ goodsClear: item.isEstmClear == 1 }">
                                        <div class="itemName"  :class="[
                                                    { itemNameChose: index == flavorIndex },
                                                    { isEstmClear : item.isEstmClear == 1 },
                                                    { operType4: operType == 4 || item.defaultQty < 1 }
                                                ]"
                                            @click="getPackFlavorS(item.goodsFlavor, index)">{{ item.goodsName }}<span
                                                v-if="item.isEstmClear == 1">(沽清)</span></div>
                                    </div>

                                    <div class="itemNum" :class="{ operType4: operType == 4 || item.isEstmClear == 1 }">
                                        <div class="reduce" @click="PackDetailReduce(index)">-</div>
                                        <div class="num">{{ item.defaultQty }}</div>
                                        <div class="add" @click="PackDetailAdd(index)">+</div>
                                    </div>
                                </div> -->
                                <div class="allocationItem" v-for="(item, index) in PackDetail" :key="index" @click="selectItem(item,modalItemData.priceList[0].detail)">
                                        <div :class="{ goodsClear: item.isEstmClear == 1 }">
                                            <div class="itemName" :class="[ { orangeBackground: (item.defaultQty > 0 && item.choiceType == '0') || (item.isSelect && item.choiceType == '1') },]" >
                                            {{ item.goodsName }}
                                            <span v-if="item.isEstmClear == 1">(沽清)</span>
                                            </div>
                                        </div>
                                        <div class="item-kw">
                                            <div class="item-kw-str" @click.stop="doFlavorShow(index)">口味:{{ item.flavor }}</div>
                                        </div>
                                        <div class="itemNum" :class="{ operType4: operType == 1 || item.isEstmClear == 1 }">
                                            <div class="reduce" @click="PackDetailReduce(index,item.isEstmClear,item)">-</div>
                                            <div class="num" >{{ item.defaultQty }}</div>
                                            <div class="add" @click="PackDetailAdd(index,item.isEstmClear,item)">+</div>
                                        </div>
                                        </div>
                            </div>
                            
                            <!-- 判断这个里面的itemName , item.defaultQty 等于1 的时候itemName背景色是橙色，小于1 是灰色 -->
                         
                        </div>
                    </div>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="onCancel">取 消</el-button>
                        <!-- <el-button @click="packAllSub(modalItemData.priceList[0].detail)">确 定</el-button> -->
                        <el-button class="btn_orge" @click="onConfirm(modalItemData.priceList[0].detail)">确 定</el-button>
                    </span>
                </template>
                <el-dialog title="口味选择" v-model="flavorShow" width="30%" destroy-on-close :show-close="false" center
                    style="border-radius: 10px;" class="FlavorDialog">
                      <div class="allocationTaste" v-if="PackDetail">
                            <div class="tasteTip">
                                <span v-if="PackDetail[flavorShowIndex].goodsFlavor.length == 0">商品暂无口味</span>
                                <!-- <span v-if="PackDetail[flavorShowIndex].goodsFlavor.length > 0">口味</span> -->
                            </div>
                            <div class="tasteList">
                                <div v-for="(item, index) in PackDetail[flavorShowIndex].goodsFlavor" :key="index" >
                                        <div class="tasteList-title">{{ item.Name }}</div>
                                        <div class="tasteList-li">
                                            <div  class="tasteList-li-item" :class="{ tasteActive: v.select }" v-for="(v, k) in item.sizeList" :key="k" @click="flavorSelect(item,index,v,k)">{{ v.uomName }}</div>
                                        </div>
                                        
                                </div>
                            </div>
                    </div>
                </el-dialog>
    </el-dialog>
</template>
<script setup>

const props = defineProps({
    modalItemData: {
        type: Object,
        required: true
    },
    toolPackDetail: {
        type: Object,
        required: true
    }
})

const modalItemData = toRef(props, 'modalItemData')
const toolPackDetail = toRef(props, 'toolPackDetail')
const PackDetail = ref(toolPackDetail.value)



// 选择套餐
const PackIndex = ref(0)
const operType = ref('')
const chosePackIndex = ref(0)
const chosePack = (detail, index) => {
   console.log(detail, index);
   chosePackIndex.value = index
//    let choiceType  = modalItemData.value.priceList[0].detail[index].choiceType
    operType.value = modalItemData.value.priceList[0].detail[index].operType
    PackIndex.value = index
    flavorIndex.value = 0
    PackDetail.value = detail
    // PackDetail.value.map(item=>{
    //     item.choiceType = choiceType
    //     item.operType = operType.value
    //     if(!(item.isSelect == false || item.isSelect == true)){
    //         item.isSelect = false
    //     }
    // })
    console.log(PackDetail.value);
    console.log(detail);
    console.log(modalItemData.value.priceList[0]);
    // if(detail.hasChangeFlo){ // 是否已经改造过口味
    //     return
    // }
    // detail.hasChangeFlo = true
    // getPackFlavorS(detail)
}

const selectItem = (v,item)=>{
    console.log(v);
    console.log(item[chosePackIndex.value]);
    
    if(v.choiceType == '0' || v.operType == '1'){
        return
    }
    const selectedCount = item[chosePackIndex.value].goodsDetail.filter(item => item.isSelect === true).length;
    if(selectedCount >= item[chosePackIndex.value].maxQty && !v.isSelect == true){
        ElNotification({
            title: '提示',
            message: '已达到最大可选数量',
            type: 'error',
        }) 
        return
    }
    v.isSelect = !v.isSelect
}

const hasInitialized = ref(false); // 标志变量
setTimeout(()=>{
    chosePack(toolPackDetail.value, 0);
},0)


// ------------------------------------------------------------ 口味选择 ---------------------------------------------------------
const flavorShow = ref(false)
const flavorShowIndex = ref(0)
const doFlavorShow = (index)=>{
    
    flavorShowIndex.value = index

    if(PackDetail.value[flavorShowIndex.value].goodsFlavor.length == 0){
        ElNotification({
            title: '提示',
            message: '商品暂无口味',
            type: 'warning',
        }) 
        return
    }
    flavorShow.value = true
    
}

const flavorSelect = (item,index,v,k)=>{
    console.log(PackDetail.value[flavorShowIndex.value]);
    
    // const detail = comboData.priceList[0].detail[groupK].goodsDetail[k]
    const flavorItem = PackDetail.value[flavorShowIndex.value].goodsFlavor[index]
    console.log(flavorItem);
    
    
    // IsMultiple 0 单选 1多选
    if(flavorItem.IsMultiple == '0'){
        // 单选除了被点击的那个 其它都为false
        for (let i = 0; i < flavorItem.sizeList.length; i++) {
            if (i != k) {
                flavorItem.sizeList[i].select = false;
            } 
        }
    }
    v.select = !v.select 
    // console.log(detail.flavor);
    // console.log(detail.goodsFlavor);
 
    const result = PackDetail.value[flavorShowIndex.value].goodsFlavor.map(vitem => {
        // 获取 sizeList 中 select 为 true 的 uomName 并拼接成字符串
        const flavor = vitem.sizeList
            .filter(obj => obj.select)        // 过滤出 select 为 true 的对象
            .map(obj => obj.uomName)          // 提取每个符合条件的 uomName
            .join(',');                       // 使用 ',' 连接成一个字符串
        
        return flavor;                      // 直接返回拼接后的字符串
    });
    console.log(result);
    
    PackDetail.value[flavorShowIndex.value].flavor = result.filter(obj => obj).join(',');
    
}   





// watch(() => props.modalItemData, async (newVal,oldValue) => {
//     console.log(newVal,oldValue);
//     if(hasInitialized.value){
//         return
//     }
    
//     if (toolPackDetail.value) {
//           chosePack(toolPackDetail.value, 0);
//           hasInitialized.value = true
//     }
   
//     }, { deep: true });

// 获取套餐单品口味
const flavorIndex = ref(0)
// const getPackFlavorS = (detail) => {
//     console.log(detail);
//     detail.forEach(detailV=>{
//         let flavor = detailV.goodsFlavor
//         if (flavor) {
//             let newFlavor = ''
//             if (typeof (flavor) == 'string') {
//                 newFlavor = JSON.parse(flavor)
//             } else {
//                 newFlavor = flavor
//             }
//             newFlavor.map(e => {
//                 if (e.flavorState == undefined) {
//                     e.flavorState = false
//                 }
//             })
//             console.log(newFlavor);
//             newFlavor.forEach(item=>{
//                 if(typeof item.FlavorStr == 'string'){
                            
//                             const str = item.FlavorStr;
        
//                             // 替换中文逗号为英文逗号
//                             const normalizedStr = str.replace(/[，,]/g, ',');
//                             // 使用英文逗号分隔字符串
//                             const parts = normalizedStr.split(',');
//                             // 将每个部分转换为对象
//                             const result = parts.map(part => {
//                                 // 默认值
//                                 let uomName = part.trim();
//                                 let addprice = 0;
//                                 let select = false;
//                                 // 检查是否有#，设置select
//                                 if (uomName.includes('#')) {
//                                     select = true;
//                                     uomName = uomName.replace('#', '').trim();
//                                 }
//                                 // 检查是否有*，设置addprice
//                                 const match = uomName.match(/\*(\d+)$/);
//                                 if (match) {
//                                     addprice = parseInt(match[1], 10);
//                                     uomName = uomName.replace(match[0], '').trim();
//                                 }
//                                 return { uomName, addprice, select };
//                             });
//                             console.log(result);
                            
//                             item.sizeList = result
                            
//                 }
//             })
            
//             // PackFlavor.value = newFlavor
//             detailV.goodsFlavor = newFlavor

//             const result = newFlavor.map(vitem => {
//             // 获取 sizeList 中 select 为 true 的 uomName 并拼接成字符串
//             const flavor = vitem.sizeList
//                 .filter(obj => obj.select)        // 过滤出 select 为 true 的对象
//                 .map(obj => obj.uomName)          // 提取每个符合条件的 uomName
//                 .join(',');                       // 使用 ',' 连接成一个字符串
            
//             return flavor;                      // 直接返回拼接后的字符串
//             });
//             console.log(result);
            
//             detailV.flavor = result.filter(obj => obj).join(',');
//             console.log(detailV)
//         }
//     })
   
// }

const PackDetailAdd = (index,isEstmClear,item) => {
    console.log(operType.value,isEstmClear);
    
    if(operType.value == 1 || isEstmClear == 1 || item.choiceType == '1'){
        return
    }
    let maxQty = modalItemData.value.priceList[0].detail[PackIndex.value].maxQty
    let num = 0
    console.log(PackDetail.value);
    
    PackDetail.value.map(e => {
        if(e.isEstmClear != '1'){
            num = num + Number(e.defaultQty)
        }
        
    })
    if (num >= maxQty) {
        console.log(num, maxQty)
    } else {
        // PackDetail.value[index].defaultQty ++
        modalItemData.value.priceList[0].detail[PackIndex.value].goodsDetail[index].defaultQty++
        modalItemData.value.priceList[0].detail[PackIndex.value].allQty++
    }
}

const PackDetailReduce = (index,isEstmClear,item) => {
    console.log(item);
    
    if(operType.value == 1 || isEstmClear == 1 || item.choiceType == '1'){
        return
    }
    if (PackDetail.value[index].defaultQty > 0) {
        // PackDetail.value[index].defaultQty --
        modalItemData.value.priceList[0].detail[PackIndex.value].goodsDetail[index].defaultQty--
        modalItemData.value.priceList[0].detail[PackIndex.value].allQty--
    }
}
//
const MultipleT = (item) => {
    if (item.IsMultiple == '0') {
        item.flavorState = !item.flavorState
    } else {
        PackDetail.value[flavorIndex.value].goodsFlavor.map(e => {
            e.flavorState = false
        })
        item.flavorState = true
    }
}

const emits = defineEmits(['update:show', 'cancel', 'confirm']);
const onConfirm = (itemS) => {
    if(!checkSum(itemS)){
        ElNotification({
            title: '提示',
            message: '套餐数量配置不正确，请确认数量配置状态',
            type: 'error',
        }) 
        return
    }
    if(checkEl(itemS)){
        ElNotification({
            title: '提示',
            message: '套餐内商品已被沽清',
            type: 'error',
        }) 
        return;
    }
    emits('confirm',itemS); 
}

// 判断固定套餐内部商品是否沽清
const checkEl = (arr)=>{
    
  let elNum = 0
    arr.forEach(item=>{
      if(item.operType == '1'){
        if(item.goodsDetail){
          item.goodsDetail.forEach(v=>{
            if(v.isEstmClear == '1'){
              elNum ++
            }
          })
        }
      }
    })
    if(elNum > 0){
      return true
    }else{
      return false
    }
 
}

function checkSum(arr) {
  
  // 辅助函数，用来计算 goodsDetail 中 isSelect 为 true 的元素和
  function sumOfSelectedStepNum(arr) {
    return arr.reduce((sum, obj) => {
        console.log(obj);
        
      if (obj.isSelect) {
        return sum += 1;
      }
      return sum;
    }, 0);
  }

  for (let obj of arr) {
    if (obj.goodsDetail && Array.isArray(obj.goodsDetail)) {
      // 如果 choiceType 为 0，使用原有逻辑计算 stepNum 和
      if (obj.choiceType == '0' && obj.operType == '0') {
        if ( obj.allQty != obj.maxQty) {
          return false; // 如果不等于，返回 false
        }
      }
      // 如果 choiceType 为 1，计算 isSelect 为 true 的元素和
      else if (obj.choiceType == '1' && obj.operType == '0') {
        const selectedSum = sumOfSelectedStepNum(obj.goodsDetail);
        console.log(selectedSum);
        
        if (selectedSum != obj.maxQty) {
          return false; // 如果不等于，返回 false
        }
      }
    }
  }
  return true; // 所有层级检查通过，返回 true
}

const onCancel = () => {
     emits('update:show');
     emits('cancel');
 }
const onClose = () => {
    emits('close')
    emits('update:show', false)
}
</script>
<style scoped lang="scss">
.packDialog {
    border-radius: 15px;
    overflow: hidden;
    margin: 0 auto;
    margin-top: 50px;

    .el-dialog__header {
        padding: 0;
    }

    .packContent {
        box-sizing: border-box;
        padding: 0px 40px;
        height: 720px;

        .packHead {
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #E5E5E5;
            padding-bottom: 20px;

            .packName {
                font-size: 22px;
                font-weight: bold;
                color: #212121;
            }

            .packPrice {
                color: #FF6A00;
                font-weight: bold;

                span {
                    font-size: 30px;
                }
            }
        }

        .packBody {
            display: flex;
            justify-content: space-between;
            color: #212121;
        }

        .packLeft {
            width: 38%;

            .packTip {
                font-size: 18px;
                padding: 18px 0;
            }

            .packList {
                padding-right: 20px;
                width: 104%;
                height: 560px;
                overflow-y: scroll;

                .packItem {
                    background-color: #FAFAFA;
                    box-sizing: border-box;
                    padding: 15px 20px;
                    border-radius: 10px;
                    margin-bottom: 20px;
                    cursor: pointer;

                    .groupTop {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;

                        .groupName {
                            font-size: 18px;
                        }

                        .groupCount {
                            span {
                                font-size: 18px;
                                padding-left: 8px;
                            }
                        }
                    }

                    .groupbottom {
                        background-color: #F2F2F2;
                        border-radius: 10px;
                        box-sizing: border-box;
                        padding: 10px 20px;
                        margin-top: 15px;
                        margin-bottom: 6px;

                        .groupGoods {
                            display: flex;
                            align-items: center;
                            line-height: 2.4;

                            .goodsName {
                                width: 60%;
                            }

                            .goodsCount {
                                width: 30%;
                                text-align: center;
                                color: #FF6A00;
                            }

                            .goodsunit {
                                width: 10%;
                                text-align: right;
                            }
                        }
                    }
                }

                .packItemChose {
                    background-color: #FFF4BF;

                    .groupbottom {
                        background-color: #FFFBE5;
                    }
                }
            }
            .packList::-webkit-scrollbar {
              display: none; /* 针对 WebKit 浏览器隐藏滚动条 */
              }
        }

        .packRight {
            width: 57%;

            // height: 500px;
            .allocationTip {
                font-size: 18px;
                padding: 18px 0;
                border-bottom: 1px solid #E5E5E5;
            } 
        .allocationList::-webkit-scrollbar { 
          width: 12px;
          height: 4px;
        }
  
        .allocationList::-webkit-scrollbar-track {
          background: #f1f1f1;
        }

        .allocationList::-webkit-scrollbar-thumb {
          background: #c1c1c1;
          border-radius: 10px;
        }

            .allocationList {
                display: grid;
                grid-template-columns: repeat(3, 28.5%);
                justify-content: space-between;
                grid-gap: 20px 0;
                padding: 20px 0;
                max-height: 550px;
                overflow-y: auto;
                overflow-x: hidden;
                // scrollbar-width: none;
                // border-bottom: 1px solid #E5E5E5; 

                .allocationItem {
                    // background-color: #F2F2F2;
                    text-align: center;
                    .item-kw{
                        display: flex;
                        align-items: center;
                        justify-content: flex-start;
                        padding: 10px 0 0;
                        .item-kw-str{
                            font-family: Microsoft YaHei;
                            font-weight: 400;
                            font-size: 16px;
                            color: #ff6900;
                            line-height: 16px;
                            cursor: pointer;
                            min-width: 180px;
                            height: 32px;
                            line-height: 24px;
                            text-align: left;
                        }
                    }
                    // border: 1px solid #E6E6E6;
                    .itemName {
                        background-color: #F2F2F2;
                        border: 1px solid #E6E6E6;
                        // border-color: #FFE566;
                        padding: 20px 0;
                        border-radius: 10px;
                        cursor: pointer;
                    }

                    .itemNameChose {
                        background-color: #FFE566;
                        border-color: #FFE566;
                    }
                    .operTypeGay {
                          background-color: #f2f2f2;
                    }

                    .itemNum {
                        display: flex;
                        align-items: center;
                        border: 1px solid #DFDFDF;
                        border-radius: 5px;
                        margin-top: 15px;

                        .reduce {
                            width: 25%;
                            border-right: 1px solid #DFDFDF;
                            padding: 10px 0;
                            cursor: pointer;
                        }

                        .num {
                            width: 50%;
                        }

                        .add {
                            width: 25%;
                            border-left: 1px solid #DFDFDF;
                            padding: 10px 0;
                            cursor: pointer;
                        }
                    }

                    .goodsClear {
                        pointer-events: none;
                        // background-color: rgba(0,0,0,0.4);
                        border-radius: 10px;
                        overflow: hidden;

                        .itemName {
                            background-color: #eee;
                            border: 1px solid #ddd;
                        }

                        .itemNameChose {
                            background-color: #eee;
                            border-color: #ddd;
                        }
                    }
                      .isEstmClear  {
                        background-color: #FFE566;
                        border-color: #FFE566;
                      }
                    .operType4 {
                        background-color: #F2F2F2;
                        // border: 1px solid #ddd;
                        // background: red;
                        // pointer-events: none;

                        .reduce {
                            border-color: #ddd;
                        }

                        .add {
                            border-color: #ddd;
                        }
                    }
                }

                // .allocationItem:nth-child(1){
                //     background-color: #FFE566;
                //     border-color: #FFE566;
                // }
                // .allocationItem:nth-child(3){
                //     background-color: #FFE566;
                //     border-color: #FFE566;
                // }
            }

            .allocationTaste {
                .tasteTip {
                    padding: 20px 0;
                }

                .tasteList {
                    display: flex;
                    align-items: center;
                    flex-wrap: wrap;

                    .tasteActive {
                        background-color: #FFE566;
                    }

                    div {
                        background-color: #E6E6E6;
                        min-width: 100px;
                        text-align: center;
                        margin-right: 15px;
                        padding: 12px 20px;
                        border-radius: 6px;
                        margin-bottom: 15px;
                        cursor: pointer;
                    }
                }
            }
        }
    }
}

.dialog-footer {
    display: block;
    padding-bottom: 20px;
    .btn_orge {
      background: #ff6900;
      color: #fff !important;
    }
    .el-button {
        width: 160px;
        height: 60px;
        font-size: 26px;
        border-color: #FF6A00;
        color: #FF6A00;
        border-radius: 10px;
    }

    .el-button:hover {
        background-color: #FF6A00;
        color: #fff;
    }

    .el-button+.el-button {
        margin-left: 30px;
    }
}
.allocationTaste {
               
                .tasteList {
                    padding: 0 20px;
                    // display: flex;
                    // align-items: center;
                    flex-wrap: wrap;
                    .tasteList-title{
                        font-family: Microsoft YaHei;
                        font-weight: 400;
                        font-size: 18px;
                        color: #212121;
                        line-height: 18px;
                        padding: 20px 0;
                    }
                    .tasteList-li{
                        display: flex;
                        align-items: center;
                        
                        .tasteList-li-item{
                            width: 80px;
                            height: 40px;
                            background: #E6E6E6;
                            border-radius: 8px;
                            text-align: center;
                            line-height: 40px;
                            cursor: pointer;
                            margin-right: 20px;
                            &.tasteActive {
                                background: #FFE566 ;
                            }
                        }
                    }
                    
                }
            }
.orangeBackground {
  border: 0px solid #E6E6E6 !important;
  background-color: #FFE566 !important;
}

</style>